import requests
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

# === 配置中心（关键修改：接口换为正式版api，修复AQI逻辑） ===
CITY_CODE = "北京丰台"  # 北京丰台（支持行政区划码/经纬度/城市名，若失败试"北京丰台"）
HEFENG_KEY = "5635e3c60cce473e8d9a3975103840ec"  # 从控制台复制的API KEY
SEND_EMAIL = "2039352976@qq.com"
EMAIL_PASSWORD = "glumlflkiezkdfbb"  # QQ邮箱授权码（需开启SMTP）
RECEIVE_EMAIL = "491144158@qq.com"
SMTP_SERVER = "smtp.qq.com"
SMTP_PORT = 465
IMAGE_PATH = "weather_chart.png"


# === 天气数据获取（修复接口地址，增强错误调试） ===
def get_weather_data():
    url_now = f"https://api.qweather.com/v7/weather/now?location={CITY_CODE}&key={HEFENG_KEY}"
    url_forecast = f"https://api.qweather.com/v7/weather/3d?location={CITY_CODE}&key={HEFENG_KEY}"

    try:
        resp_now = requests.get(url_now, timeout=10)
        resp_forecast = requests.get(url_forecast, timeout=10)

        # 强制检查状态码（非200直接抛异常）
        resp_now.raise_for_status()
        resp_forecast.raise_for_status()

        data_now = resp_now.json()
        data_forecast = resp_forecast.json()

        if data_now["code"] == "200" and data_forecast["code"] == "200":
            return {
                "now": data_now["now"],  # 实时数据（含AQI）
                "forecast": data_forecast["daily"]  # 未来3天预报
            }
        else:
            print(f"API返回错误：\n实时天气：{data_now}\n预报：{data_forecast}")
            return None
    except requests.exceptions.RequestException as e:
        # 打印详细错误（含响应内容）
        print(f"网络请求失败：{e}")
        if e.response:
            print(f"接口响应：{e.response.text}")
        return None


# === 图表生成（逻辑不变，确保路径可写） ===
def generate_weather_chart(forecast_data):
    dates = [day["fxDate"][5:] for day in forecast_data]
    temps_high = [int(day["tempMax"]) for day in forecast_data]
    temps_low = [int(day["tempMin"]) for day in forecast_data]

    plt.figure(figsize=(8, 4))
    plt.plot(dates, temps_high, "o-", color="#FF5722", label="最高温")
    plt.plot(dates, temps_low, "o-", color="#2196F3", label="最低温")
    plt.title("未来3天温度趋势")
    plt.xlabel("日期")
    plt.ylabel("℃")
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.savefig(IMAGE_PATH, dpi=300)
    plt.close()
    return True


# === 邮件内容生成（修复AQI来源：从实时数据取） ===
def create_reminder_email(reasons, tomorrow, aqi, chart_path):
    msg = MIMEMultipart()
    msg["Subject"] = f"明日不宜跑操：{tomorrow['fxDate']}天气提醒"
    msg["From"] = SEND_EMAIL
    msg["To"] = RECEIVE_EMAIL

    html = f"""
    <html>
      <body style="font-family: Arial, sans-serif;">
        <h2 style="color: #FF4444;">⚠️ 明日不宜跑操</h2>
        <p><strong>日期：</strong>{tomorrow['fxDate']}</p>
        <p><strong>提醒原因：</strong></p>
        <ul>
          {"".join([f"<li>{reason}</li>" for reason in reasons])}
        </ul>

        <h3>详细天气情况</h3>
        <p>天气：{tomorrow['textDay']}转{tomorrow['textNight']}</p>
        <p>温度：{tomorrow['tempMin']}℃ ~ {tomorrow['tempMax']}℃</p>
        <p>风力：{tomorrow['windDirDay']} {tomorrow['windScaleDay']}级</p>
        <p>空气质量：AQI {aqi}</p>  <!-- 从实时数据取AQI -->

        <h3>未来3天温度趋势</h3>
        <img src="cid:weather_chart" alt="温度图" style="max-width:600px; margin:15px 0;">
      </body>
    </html>
    """
    msg.attach(MIMEText(html, "html", "utf-8"))

    with open(chart_path, "rb") as f:
        img = MIMEImage(f.read())
        img.add_header("Content-ID", "<weather_chart>")
        msg.attach(img)

    return msg


# === 核心判断逻辑（修复AQI传递） ===
def check_reminder_condition(weather_data):
    tomorrow = weather_data["forecast"][1]  # 明天数据（索引1）
    aqi = weather_data["now"]["aqi"]  # 从实时数据取AQI
    wind_level = int(tomorrow["windScaleDay"])
    has_rain = "雨" in tomorrow["textDay"] or "雨" in tomorrow["textNight"]

    reasons = []
    if has_rain:
        reasons.append(f"降雨（{tomorrow['textDay']}/{tomorrow['textNight']}）")
    if wind_level >= 6:
        reasons.append(f"大风（{wind_level}级）")
    if int(aqi) >= 150:
        reasons.append(f"空气污染（AQI{aqi}）")

    return {
        "should_remind": len(reasons) > 0,
        "reasons": reasons,
        "tomorrow": tomorrow,
        "aqi": aqi  # 传递AQI给邮件
    }


# === 主流程（整合AQI参数） ===
def send_weather_reminder():
    weather_data = get_weather_data()
    if not weather_data:
        return

    result = check_reminder_condition(weather_data)
    if not result["should_remind"]:
        print("✅ 明日天气正常，可正常跑操")
        return

    if generate_weather_chart(weather_data["forecast"]):
        msg = create_reminder_email(
            result["reasons"],
            result["tomorrow"],
            result["aqi"],  # 传入实时AQI
            IMAGE_PATH
        )
        try:
            with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) as server:
                server.login(SEND_EMAIL, EMAIL_PASSWORD)
                server.send_message(msg)
            print(f"邮件已发送，提醒原因：{', '.join(result['reasons'])}")
        except Exception as e:
            print(f"邮件发送失败：{e}")
    else:
        print("图表生成失败，仅发送文字提醒")


# === 立即测试 ===
if __name__ == "__main__":
    send_weather_reminder()